import csv
import os

from django.shortcuts import render, redirect, HttpResponse
from hot.forms.account import LoginForm
from django.http import JsonResponse, FileResponse
from hot import models
from django_excel import make_response


def list(request):
    """客户留言"""
    if request.method == 'GET':
        table_header = ['ID', '姓名', '电话', '内容', '操作']
        objs = models.Message.objects.all()
        return render(request, 'account/liuyan.html', {'pager': objs, 'table_header': table_header})


def delete(request):
    index_id = int(request.POST.get('index_id'))
    models.Message.objects.filter(msg_id=index_id).delete()
    return JsonResponse({"code": '200'})


def delete_all(request):
    lst = request.POST.getlist('selected_ids[]')
    for i in lst:
        models.Message.objects.filter(msg_id=i).delete()
    return JsonResponse({"code": '200'})


def export(request):
    # 生成csv文本
    # 生成response的content-type头
    res = HttpResponse(content_type='text/csv')
    # 固定格式,添加 content-Disposition头，设置以附件方式下载，并给文件添加默认文件名
    res['Content-Disposition'] = 'attachment;filename="data.csv"'
    # 获取数据库中数据
    users = models.Message.objects.all()
    # 生成writer的写对象
    writer = csv.writer(res)
    # 写csv表头，即想要展示字段名
    writer.writerow(['姓名', '手机号', '邮箱', '内容'])
    # 写具体数据
    for user in users:
        writer.writerow([user.msg_name, user.msg_phone, user.msg_text])
    return res
